import proj4 from 'proj4';
import {register} from 'ol/proj/proj4'
import { Projection,addProjection} from 'ol/proj';
import TileLayer from 'ol/layer/Tile';
import TileGrid from 'ol/tilegrid/TileGrid';
import VectorTileLayer from 'ol/layer/VectorTile';
import {XYZ} from 'ol/source';
import {TileSuperMapRest} from "@supermap/iclient-ol";
// import {VectorTileSuperMapRest,VectorTileStyles} from "@supermap/iclient-ol";
import {VectorTileStyles} from "@/map/VectorTileStyles";
import {VectorTileSuperMapRest} from "@/map/VectorTileSuperMapRest";

//将4490注册到projection中
proj4.defs("EPSG:4490","GEOGCS[\"China Geodetic Coordinate System 2000\",DATUM[\"China_2000\",SPHEROID[\"CGCS2000\",6378137,298.257222101,AUTHORITY[\"EPSG\",\"1024\"]],AUTHORITY[\"EPSG\",\"1043\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4490\"]]");
register(proj4);

//重写projection4490
let projection = new Projection({
    code: 'EPSG:4490',
    units: 'degrees',
    axisOrientation: 'neu'
});
projection.setExtent([-180, -90, 180, 90]);
projection.setWorldExtent([-180, -90, 180, 90]);
//覆盖添加到projection中
addProjection(projection);

export function getProjection() {
    return projection
}

//地图服务网址
export function iServerHttp(){
    // return "http://10.13.155.192:8090"
    //代理
    return "http://10.7.208.233:8080"
}

//米转度
export function meterToDegree(meter) {
    let degree = meter / (Math.PI * 2 * 6378137 / 360);

    return degree;
}

//度转米
export function degreeToMeter(degree) {
    let meter = degree * (Math.PI * 2 * 6378137 / 360);

    return meter;
}

//自定义比例尺（天地图fxpc）
export function getResolutions() {
    let resolutions = [];
    //MVT 矢量瓦片第0级分辨率为全球范围宽度除以瓦片宽度512.
    //常见坐标系第0级分辨率   WebMercator(3857):2*6378137*Math.PI/512    WGS84(4326):360.0/512    China2000(4490):360.0/512    Beijing54(4214):360.0/512     Xian80(4610):360.0/512
    let topResolution = 360.0 / 512;
    for (let z = 0; z < 18; z++) {
        let resolution = topResolution / Math.pow(2, z);
        resolutions[z] = resolution;
        let dpi = 96;//超图使用，防止图层偏移
        // let dpi = 90.7142857142857;//自定义比例尺
        // let scale = 1 / (resolution / 0.0254 * dpi * (2 * Math.PI * 6378137) / 360);
    }

    return resolutions;
}

function getMatrixIds() {
    let matrixIds = [];
    for (let z = 0; z < 18; ++z) {
        matrixIds[z] = z;
    }
    return matrixIds;
}

//获取tileGrid（自定义比例尺）
export function getTileGrid(origin,extent) {
    return new TileGrid({
        origin: origin,
        extent: extent,
        resolutions: getResolutions(),
        matrixIds: getMatrixIds(),
        tilesSize: [256, 256]
    });
}

//fxpc天地图街道地图底图
export function getTiandituVecMap(){
    return new TileLayer({
        title: '天地图街道地图底图',
        source: new XYZ({
          crossOrigin: 'Anonymous', // 是否请求跨域操作
          url: 'http://t0.tianditu.gov.cn/vec_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=0bfd57475542d76f12578a701d2a70ab',
          projection: getProjection()
        })
    });
}

//fxpc天地图街道地图注记
export function getTiandituVecText(){
    return new TileLayer({
        title: '天地图街道地图注记',
        source: new XYZ({
            crossOrigin: 'Anonymous', // 是否请求跨域操作
            url: 'http://t0.tianditu.gov.cn/cva_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=0bfd57475542d76f12578a701d2a70ab',
            projection: getProjection()
        })
    });
}

//fxpc天地图卫星影像底图
export function getTiandituImgMap(){
    return new TileLayer({
        title: '天地图卫星影像底图',
        source: new XYZ({
            crossOrigin: 'Anonymous', // 是否请求跨域操作
            url: 'http://t0.tianditu.gov.cn/img_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=0bfd57475542d76f12578a701d2a70ab',
            projection: getProjection()
        })
    });
}

//fxpc天地图卫星影像注记
export function getTiandituImgText(){
    return new TileLayer({
        title: '天地图卫星影像注记',
        source: new XYZ({
            crossOrigin: 'Anonymous', // 是否请求跨域操作
            url: 'http://t0.tianditu.gov.cn/cia_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=0bfd57475542d76f12578a701d2a70ab',
            projection: getProjection()
        })
    });
}

//获取超图发布的REST图层（自定义比例尺）
export function getRESTLayer(layerUrl,layerID,origin,extent,serviceResult,maxZoom) {
    //获取tileGrid（自定义比例尺）
    let tileGrid = getTileGrid(origin,extent);
    if(layerID==null){//临时图层ID
        layerID = "";
    }

    // let tileOptions = TileSuperMapRest.optionsFromMapJSON(layerUrl, serviceResult);
    //自定义瓦片参数对象
    let tileOptions = {};
    tileOptions.url = layerUrl;
    tileOptions.crossOrigin = 'anonymous';
    tileOptions.tileGrid = tileGrid;
    tileOptions.layersID = layerID;//临时图层ID
    tileOptions.projection = projection;//设置projection4490
    tileOptions.dpi = 96;//超图使用，防止图层偏移
    tileOptions.cacheEnabled = false;//是否使用缓存
    return new TileLayer({
        source: new TileSuperMapRest(tileOptions),
        projection: projection
    });
}

//获取超图发布的REST矢量切片图层（自定义比例尺）
export function getVectorTileLayer(map,layerUrl,origin,extent,view,serviceResult,sqlText,minZoom) {
    //处理sql对象
    let sqlObjArray = [];
    if(sqlText!=null && sqlText!==""){
        let sqlArray = sqlText.split("and");
        for(let i=0;i<sqlArray.length;i++){
            let sqlStrArr = sqlArray[i].trim().split(" like ");
            let fieldProp = sqlStrArr[0];
            let fieldValue = sqlStrArr[1];
            let sqlObj = {
                fieldProp:fieldProp,
                fieldValue:fieldValue
            }
            sqlObjArray.push(sqlObj);
        }
    }
    /*//test
    sqlObjArray = [{
        fieldProp:"name",
        fieldValue:"'%北京%'"
    }];*/
    console.log("sqlObjArray");
    console.log(sqlObjArray);
    //矢量瓦片风格参数对象
    let stylesOptions = {
        url: layerUrl,
        view: view
    };
    //创建瓦片风格对象
    let vectorTileStyles = new VectorTileStyles(stylesOptions);
    console.log("vectorTileStyles");
    console.log(vectorTileStyles);
    //通过地图信息获取瓦片参数对象
    // let vectorTileOptions = VectorTileSuperMapRest.optionsFromMapJSON(layerUrl, serviceResult);
    //自定义瓦片参数对象
    let vectorTileOptions = {};
    vectorTileOptions.url = layerUrl;
    vectorTileOptions.crossOrigin = 'anonymous';
    //获取tileGrid（自定义比例尺）
    let tileGrid = getTileGrid(origin,extent);
    vectorTileOptions.tileGrid = tileGrid;
    vectorTileOptions.sqlObjArray = sqlObjArray;//设置sql查询对象数组
    vectorTileOptions.projection = projection;//设置projection4490
    // vectorTileOptions.view = view;
    // vectorTileOptions.minZoom = 10;//最小显示的地图级别
    console.log("vectorTileOptions");
    console.log(vectorTileOptions);
    let source = new VectorTileSuperMapRest(vectorTileOptions);//重写tileUrlFunction、tileLoadFunction（自定义比例尺）
    console.log("source");
    console.log(source);

    //返回超图发布的REST矢量切片图层（自定义比例尺）
    let layer = new VectorTileLayer({
        minZoom:minZoom,
        source: source,
        style: vectorTileStyles.featureStyleFuntion
    });

    return [layer,vectorTileStyles];
}
